package com.tuo51.evaluate.repositories.tags;

import com.tuo51.evaluate.domain.tags.RelObjectTag;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository

//@CacheConfig(cacheNames = "RelObjectTagRepository")
public interface RelObjectTagRepository extends JpaRepository<RelObjectTag, String>, JpaSpecificationExecutor<RelObjectTag> {

    @Query(value = "SELECT r.`objId`, r.id, r.`tagId` ,r.`objType` " +
            " FROM `mrel_object_tag` r " +
            " WHERE r.`objType` = ?1 GROUP BY r.`objId` order by id DESC " +
            " LIMIT ?2, ?3", nativeQuery = true)
    List<RelObjectTag> findAllByObjTypeDistinctObjId(Integer objType, Integer start, Integer length);

    @Query(value = "SELECT r.`objId`, r.id, r.`tagId` ,r.`objType` " +
            " FROM `mrel_object_tag` r GROUP BY r.`objId` " +
            " ORDER BY id DESC " +
            " LIMIT ?1, ?2", nativeQuery = true)
    List<RelObjectTag> findAllDistinctObjId(Integer start, Integer length);

    @Query(value = "SELECT count(DISTINCT(r.objId)) FROM `mrel_object_tag` r", nativeQuery = true)
    long countAllDistinctObjId();

    @Query(value = "SELECT count(DISTINCT(r.objId)) FROM `mrel_object_tag` r where r.`objType` = ?1", nativeQuery = true)
    long countAllByObjTypeDistinctObjId(Integer objType);

    RelObjectTag findByTagIdAndObjIdAndObjType(String tagId, String objId, Integer objType);

//    @Cacheable(keyGenerator = "keyGenerator")
    @Query(value = "SELECT * FROM `mrel_object_tag` WHERE `tagId` IN (" +
            "SELECT `tagId`  FROM `mrel_object_tag` WHERE `objId` = ?1 and `objType` = ?2" +
            ") and `objType` = ?3", nativeQuery = true)
    List<RelObjectTag> findAllBySourceObjectIdAndType(String objId, Integer sourceType, Integer targetType);

//    @Cacheable(keyGenerator = "keyGenerator")
    @Query(value = "SELECT * FROM `mrel_object_tag` WHERE `tagId` IN (" +
            "SELECT `tagId`  FROM `mrel_object_tag` WHERE `objId` in ?1 and `objType` = ?2" +
            ") and `objType` = ?3  ORDER BY RAND() LIMIT 10", nativeQuery = true)
    List<RelObjectTag> findAllBySourceObjectIdsAndType(List<String> objIds, Integer sourceType, Integer targetType);

    List<RelObjectTag> findAllByObjIdAndObjType(String objId, Integer objType);

    List<RelObjectTag> findAllByObjIdAndObjTypeAndTagId(String objId, Integer objType, String tagId);

}
